package com.happy3w.cmds.component.output;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Path;

public class FileTextOutput implements TextOutput {

    private final FileWriter fileWriter;

    public FileTextOutput(String filePath) {
        this(Path.of(filePath));
    }

    public FileTextOutput(Path filePath) {
        try {
            File targetFile = filePath.toFile();
            targetFile.getParentFile().mkdirs();
            this.fileWriter = new FileWriter(targetFile);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void outputLine(String line) {
        try {
            fileWriter.write(line);
            fileWriter.write("\n");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void close() {
        try {
            fileWriter.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
